import { App, Button } from 'antd'
import cs from 'classnames'
import Image from 'next/image'
import { useContext, useEffect, useRef, useState } from 'react'
import OtpInput from 'react18-input-otp'

import { OtpCreate } from '@/api/modules/entity'
import arrowNext from '@/assets/images/arrow-next.png'
import arrowPre from '@/assets/images/arrow-pre.png'
import { GlobalContext } from '@/context'
import locale from '@/pages/entity/locale'
import styles from '@/pages/entity/style/index.module.less'
import useLocale from '@/utils/useLocale'

export default function SmsCode({
  mobile,
  email,
  code,
  onChange,
}: {
  mobile?: string
  email: string
  code: string | undefined
  // eslint-disable-next-line no-unused-vars
  onChange: (setup: number, code: string) => void
}) {
  const t = useLocale(locale)
  const { message } = App.useApp()
  const [verificationCodes, setVerificationCodes] = useState<string>('')
  const smsCode = useRef<string>()

  //手动输入
  const onChangeSmsCode = (e: string) => {
    setVerificationCodes(e)
    smsCode.current = e
    if (smsCode.current.length === 6) {
      onNext()
    }
  }
  const onNext = () => {
    if (smsCode.current && smsCode.current.length === 6) {
      onChange(2, smsCode.current)
    } else {
      message.warning(t['from.verify.warning'])
    }
  }
  const onPrev = () => {
    onChange(1, '')
  }

  const maskPhoneNumber = (phoneNumber: string | undefined) => {
    if (phoneNumber && phoneNumber.length >= 4) {
      return '******' + phoneNumber.slice(-4)
    } else {
      return phoneNumber
    }
  }

  const maskEmail = (email: string | undefined) => {
    if (email) {
      const atIndex = email.indexOf('@')
      return '***' + email.substring(atIndex)
    } else {
      return email
    }
  }

  const [time, setTime] = useState(120)
  let timer: any

  useEffect(() => {
    if (code) {
      smsCode.current = code
      setVerificationCodes(code!)
    }
  }, [code])

  useEffect(() => {
    const handleKeyPress = (event: any) => {
      if (event.keyCode == 13) {
        onNext()
      }
    }
    document.addEventListener('keydown', handleKeyPress)
    return () => {
      document.removeEventListener('keydown', handleKeyPress)
    }
  }, [])
  useEffect(() => {
    timer = setInterval(() => {
      if (time > 0) setTime(time - 1)
    }, 1000)
    return () => {
      clearInterval(timer)
    }
  }, [time])

  const [loading, setLoading] = useState<boolean>(false)

  const sendSms = () => {
    setLoading(true)
    OtpCreate({ email: email })
      .then((res) => {
        setLoading(false)
        setTime(120)
        const { code } = res.data
        smsCode.current = code
        setVerificationCodes(code!)
      })
      .catch(() => {
        setLoading(false)
      })
  }

  const { lang } = useContext(GlobalContext)

  return (
    <div
      className={cs(
        'w-full flex flex-col justify-center items-center px-[271px]',
        styles['sms-code']
      )}
    >
      <div className="text-[#000] text-[30px] Roboto font-bold">{t['smsCode.title']}</div>
      <div className={cs('py-4 text-[14px] Avenir grey', styles['grey'])}>
        {t['smsCode.desc']}
        {/* {maskPhoneNumber(mobile)} */}
        {/* {maskEmail(email)} */}
        {email}
        {t['smsCode.desc1']}
      </div>
      <OtpInput
        containerStyle={cs(styles['verification-code'], 'Roboto')}
        inputStyle={styles['verification-input']}
        value={verificationCodes}
        onChange={(e: string) => {
          onChangeSmsCode(e)
        }}
        numInputs={6}
        isInputNum={true}
        shouldAutoFocus
      />

      <div
        className={cs(
          'h-[136px] pt-[16px] pb-[80px] text-[14px] Avenir flex items-center',
          styles['grey']
        )}
      >
        {time > 0 ? (
          <>
            {time} {t['smsCode.time']}
          </>
        ) : (
          <Button
            ghost
            type="primary"
            className={styles['resend']}
            onClick={sendSms}
            loading={loading}
          >
            {t['smsCode.resend']}
          </Button>
        )}
      </div>

      <div className="w-full flex justify-between ">
        <Button ghost type="primary" className={cs(styles['previous'])} onClick={onPrev}>
          <Image
            src={arrowPre}
            alt="pre"
            className={cs('w-4 h-3', lang === 'en-US' ? '' : 'rtl-img ')}
          />
          <span className={cs('px-2 Roboto text-[18px] font-bold')}>{t['smsCode.previous']}</span>
        </Button>
        <Button type="primary" className={cs(styles['next'])} onClick={onNext}>
          <span className={cs('px-2 Roboto text-[18px] font-bold')}>{t['smsCode.next']}</span>
          <Image
            src={arrowNext}
            alt="next"
            className={cs('w-4 h-3', lang === 'en-US' ? '' : 'rtl-img ')}
          />
        </Button>
      </div>
    </div>
  )
}
